<template>
  <article>
    <el-row style="padding-left: 3em;text-align: left;padding-top: 1em">
      <el-form :model="form" ref="form" label-width="150">
        <el-row>
          <el-col :span="10">
            <el-form-item label="日期范围:">
              <el-date-picker
                id="id-creativerepost-componets-edit_chars-searchForm"
                style="width: 60%;"
                v-model="form.date"
                size="mini"
                type="daterange"
                align="left"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                @change="searchForm">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-row>
    <el-row class="charts">
      <div>分天数据</div>
      <div id="dataLine" ref="dataLine" :loading="dataLineLoading" :style="{width: '1100px', height: '400px'}"></div>
    </el-row>
<!--    <el-row class="charts">-->
<!--      <div>每日在线广告数</div>-->
<!--      <div id="onlineAd" ref="onlineAd" :loading="onlineAdeLoading" :style="{width: '1100px', height: '400px'}"></div>-->
<!--    </el-row>-->
    <el-row class="charts">
      <div>优化师消耗分布</div>
      <div id="optimizerSpend" ref="optimizerSpend" :loading="optimizerSpendLoading" :style="{width: '1100px', height: '400px'}"></div>
    </el-row>
  </article>
</template>

<script>
import * as echarts from 'echarts';
import Moment from "moment";
import {getCreativePerformanceList, getOptimizerSpendList} from "@/api/offer/creativeperformance";

export default {
  name: "tags_chars",
  props:{
    creativeId: String,
  },
  data() {
    return {
      dataLineLoading: false,
      onlineAdeLoading: false,
      optimizerSpendLoading: false,
      form: {
        date: []
      },
      query: {},
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '过去三十天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(1, "months").toDate();
            let end = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '过去十四天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(14, "days").toDate();
            let end = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '过去七天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(7, "days").toDate();
            let end = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, end]);
          }
        },{
          text: '昨天',
          onClick(picker) {
            let start = Moment(new Date()).subtract(1, "days").toDate();
            picker.$emit('pick', [start, start]);
          }
        },{
          text: '今天',
          onClick(picker) {
            let start = new Date();
            picker.$emit('pick', [start, start]);
          }
        }]
      },
    }
  },
  created() {
    let start = Moment(new Date()).subtract(7, "days").toDate();
    let end = Moment(new Date()).subtract(1, "days").toDate();
    this.form.date = [start,end];
  },
  mounted() {
    this.searchForm();
  },
  methods: {
    getEchartsInst(eleName) {
      let ele = document.getElementById(eleName);
      let myInst = echarts.getInstanceByDom(ele);
      if (myInst) {
        return myInst;
      } else {
        return echarts.init(ele);
      }
    },
    loadCreativePerformanceList(data) {
      if(data == null) {
        this.dataLineLoading = true;
        this.onlineAdeLoading = true;
        let query = {
          creativeId: this.creativeId,
          beginDate: this.query.beginDate,
          endDate: this.query.endDate,
        };
        getCreativePerformanceList(
          Object.assign({}, query)
        ).then((res) => {
          if(res.data.data != null) {
            res.data.data.forEach(row=>{
              row.reportDate = Moment(row.reportDate).format('YYYY-MM-DD');
            });
            this.loadCreativePerformanceList(res.data.data);
          }
        }).finally(()=>{
          this.dataLineLoading = false;
          this.onlineAdeLoading = false;
        });
        return;
      }
      this.drawDataLine(data);
      this.drawOnlineAd(data);
    },
    drawDataLine(data){
      if(data == null) {
        return;
      }
      let query = {
        creativeId: this.creativeId,
        beginDate: this.query.beginDate,
        endDate: this.query.endDate,
      };
      let reportDateList = [];
      let seriesData = {
        impressions: [],
        clicks: [],
        install: [],
        spend: [],
        ctr: [],
        cvr: [],
      };
      let checkDate = query.beginDate;
      while(checkDate<=query.endDate) {
        reportDateList.push(checkDate);
        seriesData.impressions.push(0);
        seriesData.clicks.push(0);
        seriesData.install.push(0);
        seriesData.spend.push(0);
        seriesData.ctr.push(0);
        seriesData.cvr.push(0);
        checkDate = Moment(checkDate).subtract(-1, "days").format('YYYY-MM-DD');
      }
      data.forEach(row=>{
        let colIdx = reportDateList.indexOf(row.reportDate);
        seriesData.impressions[colIdx] = row.impressions;
        seriesData.clicks[colIdx] = row.clicks;
        seriesData.install[colIdx] = row.install;
        seriesData.spend[colIdx] = row.allExpend;
        seriesData.ctr[colIdx] = row.ctr;
        seriesData.cvr[colIdx] = row.cvr;
      });
      let myChart = this.getEchartsInst('dataLine');
      let option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['曝光','点击','安装','花费','点击率','转换率'],
          selected:{ '曝光':false, '点击':false,'安装':true,'花费':true,'点击率':false,'转换率':false}
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: reportDateList
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '曝光',
            type: 'line',
            data: seriesData.impressions
          },
          {
            name: '点击',
            type: 'line',
            data: seriesData.clicks
          },
          {
            name: '安装',
            type: 'line',
            data: seriesData.install
          },
          {
            name: '花费',
            type: 'line',
            data: seriesData.spend
          },
          {
            name: '点击率',
            type: 'line',
            data: seriesData.ctr
          },
          {
            name: '转换率',
            type: 'line',
            data: seriesData.cvr
          }
        ]
      };

      option && myChart.setOption(option,true);
    },
    drawOnlineAd(data){
      if(data == null) {
        return;
      }
      let query = {
        creativeId: this.creativeId,
        beginDate: this.query.beginDate,
        endDate: this.query.endDate,
      };
      let reportDateList = [];
      let seriesData = {
        ads: [],
      };
      let checkDate = query.beginDate;
      while(checkDate<=query.endDate) {
        reportDateList.push(checkDate);
        seriesData.ads.push(0);
        checkDate = Moment(checkDate).subtract(-1, "days").format('YYYY-MM-DD');
      }
      let maxAds = 0;
      let minAds = 0;
      let colorList = ['#f2c25c','#f2cc8d','#f9e894','#e1f39b','#aed994'];
      data.forEach(row=>{
        let colIdx = reportDateList.indexOf(row.reportDate);
        seriesData.ads[colIdx] = this.countAds(row.ads);
        if(maxAds < seriesData.ads[colIdx]) {
          maxAds = seriesData.ads[colIdx];
        }
        if(minAds == 0 || minAds > seriesData.ads[colIdx]) {
          minAds = seriesData.ads[colIdx];
        }
      });
      let myChart = this.getEchartsInst('onlineAd');
      let option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}'
        },
        xAxis: {
          type: 'category',
          data: reportDateList,
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: seriesData.ads,
            type: 'bar',
            itemStyle: {
              normal: {
                color: function(params) {
                  console.log(params);
                  let pos = colorList.length - 1;
                  if(maxAds > minAds) {
                    pos = Math.floor(((params.value - minAds) * colorList.length)/ (maxAds - minAds));
                    if(pos == colorList.length) {
                      pos --;
                    }
                  }
                  return colorList[pos];
                }
              },
            },
          }
        ]
      };
      option && myChart.setOption(option);
    },
    countAds(ads) {
      let adsArr = ads.split(",");
      let res = [...new Set(adsArr)];
      return res.length;
    },

    drawOptimizerSpend(data){
      if(data == null) {
        this.optimizerSpendLoading = true;
        let query = {
          creativeId: this.creativeId,
          beginDate: this.query.beginDate,
          endDate: this.query.endDate,
        };
        getOptimizerSpendList(
          Object.assign({}, query)
        ).then((res) => {
          if(res.data.data != null) {
            this.drawOptimizerSpend(res.data.data);
          }
        }).finally(()=>{
          this.optimizerSpendLoading = false;
        });
        return;
      }

      let optimizerSpendList = [];
      data.forEach(row=>{
        optimizerSpendList.push({
          value: row.allExpend,
          name: (row.operatorName == null || row.operatorName == '')?'未知':row.operatorName,
        });
      });

      let myChart = this.getEchartsInst('optimizerSpend');
      let option = {
        title: {
          text: '优化师消耗分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: '50%',
            data: optimizerSpendList,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            label: {
              normal: {
                formatter: '{b}: {d}%'
              },
            },
          }
        ]
      };

      option && myChart.setOption(option);
    },
    searchForm(){
      if(this.form.date != null && this.form.date.length == 2) {
        this.query.beginDate = Moment(this.form.date[0]).format('YYYY-MM-DD');
        this.query.endDate =Moment(this.form.date[1]).format('YYYY-MM-DD');
        this.loadCreativePerformanceList();
      } else {
        this.query = {};
      }
      this.drawOptimizerSpend();
    }
  }
}
</script>

<style scoped lang="scss">
.charts{
  padding-top: 1.5em;
  div:nth-child(1){
    text-align: left;
    font-size: 17px;
    font-weight: 600;
    padding-bottom: 1em;
  }
}
</style>
